<template>
  <!-- 工序表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="700px"
      draggable
      @close="closeDialog"
      :destroy-on-close="true"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="工厂" prop="plantId">
              <el-select
                v-if="!props.isReadonly"
                v-model="formData.plantId"
                placeholder="请输入工厂"
                clearable
                @change="changePlant"
                style="width: 230px"
                filterable
              >
                <el-option
                  v-for="item in plantList"
                  :key="item.id"
                  :label="item.organizationCode"
                  :value="item.id"
                />
              </el-select>
              <span v-else>{{ plantCode(formData.plantId) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作中心" prop="workCenterId">
              <el-select
                v-if="!props.isReadonly"
                v-model="formData.workCenterId"
                placeholder="请输入工作中心"
                clearable
                @change="changeWorkCenter"
                :disabled="formData.plantId === ''"
                style="width: 230px"
                filterable
              >
                <el-option
                  v-for="item in workCenters"
                  :key="item.id"
                  :label="`${item.workshopCode}-${item.workshopName}`"
                  :value="item.id"
                />
              </el-select>

              <span v-else>{{ formData.workCenterCode }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="工序编号" prop="processCode">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.processCode"
                placeholder="请输入工序编号"
                clearable
              />

              <span v-else>{{ formData.processCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工序名称" prop="processName">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.processName"
                placeholder="请输入工序名称"
                clearable
              />

              <span v-else>{{ formData.processName }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="工序类型" prop="processType">
              <el-select
                style="width: 100%"
                v-if="!props.isReadonly"
                v-model="formData.processType"
                placeholder="请选择货位类型"
                clearable
              >
                <el-option
                  v-for="item in dictionaryStore.filterDictList('ProcessType')"
                  :key="Number(item.value)"
                  :label="item.label"
                  :value="Number(item.value)"
                />
              </el-select>

              <span v-else>{{
                dictionaryStore.filterDictName(
                  "ProcessType",
                  formData.processType
                )
              }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否启用" prop="enabled">
              <el-radio-group
                v-model="formData.enabled"
                v-if="!props.isReadonly"
              >
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
              <span v-else>{{ formData.enabled == 1 ? "启用" : "停用" }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="备注" prop="remarks">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.remarks"
                placeholder="请输入备注"
                clearable
                type="textarea"
              />

              <text v-else>{{ formData.remarks }}</text>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班制" prop="mesShiftSetId">
              <el-select
                v-if="!props.isReadonly"
                v-model="formData.mesShiftSetId"
                placeholder="请选择班制"
                clearable
                @change="changeMesShiftSet"
                style="width: 230px"
                filterable
              >
                <el-option
                  v-for="item in shiftSetList"
                  :key="item.id"
                  :label="item.shiftSetName"
                  :value="item.id"
                />
              </el-select>
              <span v-else>{{ mesShiftSetId(formData.mesShiftSetId) }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-show="props.isReadonly">
          <el-col :span="12">
            <el-form-item label="创建时间" prop="createTime">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.createTime"
                placeholder="请输入创建时间"
                clearable
              />
              <span v-else>{{ formData.createTime }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建人" prop="createdUserName">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.createdUserName"
                placeholder="请输入创建人"
                clearable
              />
              <span v-else>{{ formData.createdUserName }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="props.isReadonly">
          <el-col :span="12">
            <el-form-item label="更新时间" prop="lastUpdateTime">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.lastUpdateTime"
                placeholder="请输入更新时间"
                clearable
              />
              <span v-else>{{ formData.lastUpdateTime }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="更新人" prop="lastUpdatedUserName">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.lastUpdatedUserName"
                placeholder="请输入更新人"
                clearable
              />
              <span v-else>{{ formData.lastUpdatedUserName }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <h4 class="mb-[20px] mt-[20px]">工序设备</h4>
        <el-card shadow="never" class="table-container">
          <template #header v-if="!props.isReadonly">
            <el-button type="success" plain @click="handleAdd">
              <i-ep-plus />
              新增</el-button
            >
          </template>
          <div class="formTable">
            <el-table
              :data="formData.details"
              :key="Math.random"
              border
              style="max-height: 200px; overflow: auto"
            >
              <el-table-column
                label="设备名称"
                props="equipmentName"
                align="left"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.equipmentsList'"
                    :rules="rules.equipment"
                    label-width="0px"
                  >
                    <select-device-input
                      :width="220"
                      :isMultiple="false"
                      :showSelectDevice="row.equipmentsList"
                      @get-device="
                        (id, object) => getDevice(id, object, $index)
                      "
                      :disabled="row.equipmentId != '' || props.isReadonly"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="设备编号"
                props="equipmentCode"
                align="center"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <span>{{ row.equipmentCode }}</span>
                </template>
              </el-table-column>

              <el-table-column
                fixed="right"
                align="center"
                label="操作"
                v-if="!props.isReadonly"
              >
                <template #default="scope">
                  <el-button
                    :disabled="formData.details.length < 2"
                    type="danger"
                    link
                    @click.stop="handleDelete(scope.$index)"
                    ><i-ep-delete />
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MESMESPROCESSADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

const rules = reactive({
  processCode: [
    {
      required: true,
      pattern: "[^ \x20]+",
      message: "请输入工序编号",
      trigger: "blur",
    },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  processName: [
    {
      required: true,
      pattern: "[^ \x20]+",
      message: "请输入工序名称",
      trigger: "blur",
    },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  plantId: [{ required: true, message: "请选择工厂", trigger: "change" }],
  mesShiftSetId: [{ required: true, message: "请选择班制", trigger: "change" }],
  workCenterId: [
    { required: true, message: "请选择工作中心", trigger: "change" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  enabled: [],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  processCode: "",
  processName: "",
  processType: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  workCenterId: "",
  workCenterCode: "",
  workCenterName: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  mesShiftSetId: "",
  enabled: 1,
  deleted: "",
  details: [
    // {
    //   id: "",
    //   processId: "",
    //   processCode: "",
    //   processName: "",
    //   workCenterId: "",
    //   workCenterCode: "",
    //   equipmentId: "",
    //   equipmentCode: "",
    //   equipmentName: "",
    //   organizationCode: "",
    //   organizationId: "",
    //   plantCode: "",
    //   plantId: "",
    //   remarks: "",
    //   version: 0,
    //   deleted: "",
    //   enabled: 1,
    //   ids: [],
    //   createTime: "",
    //   createdUserId: "",
    //   createdUserName: "",
    //   lastUpdateTime: "",
    //   lastUpdatedUserId: "",
    //   lastUpdatedUserName: "",
    //   equipmentsList: [],
    // },
  ],
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    //新增时清除下拉列表数据
    workCenters.value = [];
    if (newVal?.id) {
      const {
        id,
        processCode,
        processName,
        processType,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        workCenterId,
        workCenterCode,
        workCenterName,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        mesShiftSetId,
        enabled,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        processCode,
        processName,
        processType,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        workCenterId,
        workCenterCode,
        workCenterName,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        mesShiftSetId,
        enabled,
        deleted,
      });

      //编辑时查询当前工作中心id对应code
      getWorkCenter();
      getEquipmentList(newVal?.id);
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.processCode = "";
  formData.processName = "";
  formData.processType = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.workCenterId = "";
  formData.workCenterCode = "";
  formData.workCenterName = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.mesShiftSetId = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.details = [];
}

const loading = ref(false);

/** 工序保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mes/mesprocess/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

// 回显/设置设备信息

// 获取选中的数据进行回显并赋值
const noRepeat = ref(true);
function getDevice(Ids: string[], Objects: any, index: number) {
  for (let i = 0; i < formData.details.length; i++) {
    if (formData.details[i].equipmentId === Objects[0].id) {
      noRepeat.value = false;
      ElMessage.error("设备已存在，请重新选择");
      break;
    }
  }
  console.log(noRepeat.value);

  if (noRepeat.value == true) {
    console.log(noRepeat.value);

    formData.details[index].equipmentsList = Objects.map((item) => {
      return {
        id: item.id,
        equipName: item.equipName,
        equipCode: item.equipCode,
      };
    });
    formData.details[index].equipmentId = Objects[0].id;
    formData.details[index].equipmentCode = Objects[0].equipCode;
    formData.details[index].equipmentName = Objects[0].equipName;
  } else {
    formData.details[index].equipmentsList = [{}];
    noRepeat.value = true;
  }
}
/** 删除行 */
const isValidated = ref(false);
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

const details1: any = {
  id: "",
  processId: "",
  processCode: "",
  processName: "",
  workCenterId: "",
  workCenterCode: "",
  equipmentId: "",
  equipmentCode: "",
  equipmentName: "",
  organizationCode: "",
  organizationId: "",
  plantCode: "",
  plantId: "",
  remarks: "",
  version: 0,
  deleted: "",
  enabled: 1,
  ids: [],
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  equipmentsList: [],
  mesShiftSetId: "",
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details1));
  formData.details.push(sondata);
};
// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

onMounted(() => {
  getPlantList();
  getShiftSetList();
});
//工厂列表
const plantList = ref([]);
const getPlantList = async () => {
  const { data } = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = data;
};
// 班制列表
const shiftSetList = ref([]);
const getShiftSetList = async () => {
  const { data } = await request({
    url: "mes/messhiftset/getList",
    method: "post",
    data: {},
  });
  shiftSetList.value = data;
};
const changePlant = (id: any) => {
  formData.plantId = id;
  formData.plantCode = plantCode(id);
  //工厂变更清除关联内容
  formData.workCenterId = "";
  formData.workCenterCode = "";
  formData.workCenterName = "";
  workCenters.value = [];
  getWorkCenter();
};
const changeMesShiftSet = (id: any) => {
  formData.mesShiftSetId = id;
};
const plantCode = (id: string) => {
  if (id) {
    const data = plantList.value.find((item) => item.id === id);
    return data.organizationCode;
  }
};
const mesShiftSetId = (id: string) => {
  if (id) {
    const data = shiftSetList.value.find((item) => item.id === id);
    return data.shiftSetName;
  }
};
//工作中心
const workCenters = ref([]);
async function getWorkCenter() {
  if (formData.plantId) {
    await request({
      url: "mes/mesworkshop/getList",
      method: "post",
      data: { plantId: formData.plantId, enabled: 1 },
    }).then((res) => {
      workCenters.value = res.data;
    });
  }
}
const changeWorkCenter = (id: any) => {
  formData.workCenterId = id;
  workCenters.value.forEach((item) => {
    if (item.id === id) {
      formData.workCenterCode = item.workshopCode;
      formData.workCenterName = item.workshopName;
    }
  });
};

// 获取设备
const getEquipmentList = async (id) => {
  await request({
    url: `mes/mesprocessequipment/getList`,
    method: "post",
    data: { processId: id },
  }).then((res) => {
    // 有id时 发请求获取设备数据并复制
    formData.details = res.data;
    // 遍历数据 给每个数据添加equipmentsList属性 用于组件回显
    formData.details.forEach((item: any) => {
      item.equipmentsList = [
        {
          id: item.equipmentId,
          equipCode: item.equipmentCode,
          equipName: item.equipmentName,
        },
      ];
    });
  });
};
</script>
<style lang="scss" scoped>
.formTable {
  :deep(.el-form-item) {
    margin: 0 0 13px 0 !important;
  }
}

:deep(.formTable .el-table .el-form-item) {
  padding: 11px 0 0 0 !important;
}
:deep(.formTable .el-table .el-form-item__error) {
  font-size: 11px !important;
}

:deep(.formTable .el-table) {
  .el-table__body td.el-table__cell {
    // padding: 5px !important;
    padding: 0 !important;
  }
}
</style>
